import React from 'react'

// 装饰器函数，WrappedComponent是待装饰的组件
const DragHOCPlus = (WrappedComponent) => {
    return class extends React.Component {
        constructor(props) {
            super(props);
            this.state = {
                x:0,
                y:0,
                lock:false,
                startX:0,
                startY:0,
                beginX:0,
                beginY:0
            }
        }
        handleMouseDown = (e) => {
            if(!this.state.lock) {
                this.setState({
                    lock:true,
                    startX:e.touches?e.touches[0].clientX:e.clientX,
                    startY:e.touches?e.touches[0].clientY:e.clientY
                })
            }
        }
        handleMouseMove = (e) => {
            if(this.state.lock) {//移动的是moveRef
                let moveX = e.touches?e.touches[0].clientX:e.clientX,
                moveY = e.touches?e.touches[0].clientY:e.clientY;
                this.setState( oldState => ({
                    x:moveX-(oldState.startX-oldState.beginX),
                    y:moveY-(oldState.startY-oldState.beginY)
                }));
            }
        }
        handleMouseUp = (e) => {
            if(this.state.lock) {
                this.setState( oldState => ({
                    lock:false,
                    beginX:oldState.x,
                    beginY:oldState.y
                }));
            }
        }
        render () {
            return (
                <div onMouseDown={this.handleMouseDown} onTouchStart={this.handleMouseDown} onMouseUp={this.handleMouseUp} onTouchEnd={this.handleMouseUp} onMouseMove={this.handleMouseMove} onTouchMove={this.handleMouseMove} >
                    <div style={{left:this.state.x, top:this.state.y,display:'inline-block',position:'relative'}}>
                        <WrappedComponent x={this.state.x} y={this.state.y} />
                    </div>
                </div>  
            )
        }
    }
}
export default DragHOCPlus